<template>
  <el-container style="height: 100vh">
    <el-menu style="width: 200px" :default-openeds="openeds">
      <my-menu-item :menuData="menuData"></my-menu-item>
    </el-menu>

    <el-main>
      <div class="user-info"><UserInfo /></div>
      <router-view></router-view>
    </el-main>
  </el-container>
</template>

<script>
import {
  Menu,
  MenuItemGroup,
  Submenu,
  Container,
  Aside,
  Main,
} from "element-ui";
import { GetUserMenus } from "../api/Authentication";
import MyMenuItem from "../components/MyMenuItem.vue";
import UserInfo from "../components/UserInfo.vue";
import { Loading } from "element-ui";
export default {
  components: {
    [Menu.name]: Menu,
    [MenuItemGroup.name]: MenuItemGroup,
    [Submenu.name]: Submenu,
    [Container.name]: Container,
    [Aside.name]: Aside,
    [Main.name]: Main,
    MyMenuItem,
    UserInfo,
  },
  data() {
    return {
      defaultActive: "", // 可以根据需要设置默认激活的菜单项
      menuData: [],
      openeds: ["m1"],
    };
  },
  beforeCreate() {
    Loading.service({ fullscreen: true });
  },
  created() {
    this.getMenuData();
  },
  methods: {
    getMenuData() {
      GetUserMenus() // 假设你的接口地址是 '/api/menu'
        .then((result) => {
          if (result.code === 200) {
            this.menuData = this.buildMenu(result.data);
            this.defaultActive =
              this.menuData.length > 0 ? this.menuData[0].id : "";
          } else {
            console.error("Failed to fetch menu data:", result.data.message);
          }
          Loading.service().close();
        })
        .catch((error) => {
          console.error("Error fetching menu data:", error);
        });
    },
    buildMenu(data) {
      // 递归构建菜单数据
      return data.map((item) => {
        if (item.children) {
          return {
            ...item,
            children: this.buildMenu(item.children),
          };
        }
        return item;
      });
    },
  },
};
</script>

<style scoped>
.el-menu-vertical-demo:not(.el-menu--collapse) {
  width: 200px;
}
.user-info {
  position: absolute;
  right: 20px;
  top: 20px;
}
.el-main {
  padding: 0px !important;
}
</style>
